<template>
  <q-page class="q-pa-md wrapBox" v-loading="loading">
    <div class="nav">
      <el-breadcrumb separator="/">
        <el-image src="/svgs/titleIcon.svg" style="width: 17px; margin: 0 10px 0 0" fit/>
        <el-breadcrumb-item>{{ $t('dataCenter') }}</el-breadcrumb-item>
        <el-breadcrumb-item
          ><span style="color: #333">{{
            $t('featureLibrary')
          }}</span></el-breadcrumb-item
        >
      </el-breadcrumb>
    </div>
    <div class="datasetBox" style="position: relative">
      <div class="contentBox_title">{{ $t('featureLibrary') }}</div>
      <div class="contentBox">
        <el-row class="mb-4" style="margin-bottom: 15px">
          <div style="margin-top: 10px">
            <el-input
              v-model.trim="searchName"
              placeholder="搜索特征库任务名称"
              spellcheck="false"
              @keyup.enter="getDataset"
            >
              <template #prepend>
                <el-select
                  v-model="typeValue"
                  placeholder="全部"
                  style="width: 150px; background-color: #fff"
                >
                  <el-option
                    v-for="item in dataTypeData"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                    @click="getDataset"
                  />
                </el-select>
              </template>
              <template #append>
                <el-button :icon="Search" @click="getDataset" />
              </template>
            </el-input>
          </div>
          <div class="rightBox">
            <el-button
              type="primary"
              size="default"
              style="background-color: #3d5ce4; width: 80px; margin-top: 10px"
              @click="showDialog('dialogAddData', 0, '', '')"
              >{{ $t('newBuilt') }}</el-button
            >
          </div>
        </el-row>
        <el-table
          :data="tableData.results"
          style="width: 100%; font-size: 14px"
          :cell-style="cellStyle"
          :header-cell-style="{
            background: '#f9f9f9',
            color: '#333333',
            fontWeight: '500',
            fontSize: '14px',
            textAlign: 'left',
            height: '56px',
          }"
          stripe
        >
          <el-table-column align="left" prop="title" label="特征集名称">
            <template #default="{ row }">
              <el-button
                link
                type="primary"
                size="small"
                style="font-size: 14px"
                :style="row.label_task_title? '': 'cursor: no-drop;filter: grayscale(1);opacity: 0.7;'"
                @click="row.label_task_title? toDetailPage(row.id): setErrorTips(row.id)"
                >
                <span class="overFlowEllipsis">{{ row.title }}</span>
              </el-button>
            </template>
          </el-table-column>
          <el-table-column align="left" prop="source" label="特征集来源" />
          <el-table-column align="left" prop="creator" label="创建人" />
          <el-table-column
            align="left"
            prop="create_time"
            label="创建时间"
            width="200"
          />
          <el-table-column
            align="left"
            prop="description"
            label="特征集说明"
            width="200"
          >
            <template #default="scope">
              {{ scope.row.description ? scope.row.description : '-' }}
            </template>
          </el-table-column>
          <el-table-column
            align="left"
            prop="upload_status"
            label="创建状态"
            width="200"
          >
            <template #default="scope">
              <StatusBoxCpn :status="scope.row.upload_status" :gap="5" />
            </template>
          </el-table-column>

          <el-table-column align="left" prop="labels" label="操作" width="250">
            <template #default="{ row }">
              <template v-if="row.upload_status == 'success'">
                <el-button
                  v-show="userStatus ? true : row.creator == userInfoName"
                  link
                  type="primary"
                  style="font-size: 14px"
                  size="small"
                  @click="
                    showDialog(
                      'dialogSetData',
                      row.id,
                      row.title,
                      row.description
                    )
                  "
                  >编辑</el-button
                >
                <el-button
                  :disabled="!row.is_split"
                  v-show="userStatus ? true : row.creator == userInfoName"
                  link
                  type="primary"
                  style="font-size: 14px"
                  :style="
                    row.label_task_title
                      ? ''
                      : 'cursor: no-drop;filter: grayscale(1);opacity: 0.7;'
                  "
                  size="small"
                  @click="
                    row.label_task_title
                      ? showDialog('dialogSplitData', row.id, '', '')
                      : setErrorTips('拆分')
                  "
                  >拆分</el-button
                >
                <el-button
                  style="font-size: 14px"
                  v-show="userStatus ? true : row.creator == userInfoName"
                  link
                  type="primary"
                  size="small"
                  @click="downLoadData(row.id, row.title)"
                  >下载</el-button
                >
                <!-- <el-button link type="primary" size="small">复制</el-button> -->
                <el-button
                  style="font-size: 14px"
                  v-show="userStatus ? true : row.creator == userInfoName"
                  link
                  type="primary"
                  size="small"
                  @click="deleteProject(row.id)"
                  >删除</el-button
                >
              </template>
              <template v-else-if="row.upload_status == 'pause'">
                <el-button
                  v-show="
                    userStatus ? true : scope.row.creator === userInfoName
                  "
                  link
                  type="primary"
                  size="medium"
                  @click="
                    handleContinueUpload({
                      feature_set_id: row.id,
                      project_id: projectId,
                    })
                  "
                  >继续上传
                </el-button>
              </template>
              <template v-else>
                <div
                  style="
                    position: absolute;
                    top: 50%;
                    transform: translateY(-50%);
                  "
                >
                  <el-tooltip
                    class="box-item"
                    effect="light"
                    content="创建过程: Uploading -> Merging -> Importing -> Success"
                    placement="top-start"
                  >
                    <div class="d-dot" style="position: relative; left: 0">
                      <span style="color: #606266"> 飞速创建中 </span>
                      <span class="d-dot-ani"></span>
                    </div>
                  </el-tooltip>
                </div>
              </template>
            </template>
          </el-table-column>
          <template #empty>
            <div class="noData">暂无数据</div>
          </template>
        </el-table>
      </div>
      <div
        class="row"
        style="
          justify-content: flex-end;
          margin-top: 10px;
          background-color: #fff;
          padding: 10px 0;
        "
        v-if="tableData.results.length > 0"
      >
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="tableData.count"
          :page-sizes="[10, 20, 50]"
          :current-page="pageData.page"
          @current-change="changePage"
        />
      </div>
    </div>
    <div style="position: relative">
      <el-dialog
        v-model="dialogAddData"
        title="新增特征集"
        width="500"
        :show-close="true"
        :close-on-click-modal="false"
      >
        <box-loading v-if="loading" @click.stop></box-loading>
        <el-form
          ref="ruleFormRef"
          :model="formLabelAlign"
          :rules="rules"
          label-position="right"
          label-width="150px"
          style="max-width: 460px"
        >
          <el-form-item label="特征集名称：" prop="title">
            <el-input
              v-model.trim="formLabelAlign.title"
              style="width: 300px"
              placeholder="请输入特征集名称"
            />
          </el-form-item>
          <el-form-item label="说明：" prop="description">
            <el-input
              v-model="formLabelAlign.description"
              style="width: 300px"
              placeholder="说明"
            />
          </el-form-item>
          <el-form-item label="特征集来源：" style="width: 500px">
            <el-radio-group v-model.trim="seDataChoose">
              <el-radio-button label="labelData"
                >从标注任务选择</el-radio-button
              >
              <el-radio-button label="userData">本地上传</el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            label="选择标注场景："
            style="width: 500px"
            prop="dataset_type"
            v-if="seDataChoose === 'labelData'"
          >
            <el-select
              v-model.trim="formLabelAlign.dataset_type"
              class="m-2"
              placeholder="请选择数据类型"
              style="width: 300px"
              popper-class="dropdown"
            >
              <el-option label="图片" value="Image" @click="getLabelData" />
              <el-option
                label="时序数据"
                value="TimeSeries"
                @click="getLabelData"
              />
              <el-option
                label="序列/结构文件"
                value="Text"
                @click="getLabelData"
              />
            </el-select>
          </el-form-item>
          <div v-if="seDataChoose == 'labelData'">
            <transition name="el-fade-in">
              <el-form-item label="选择标注任务：" prop="label_task">
                <el-select
                  v-model="formLabelAlign.label_task"
                  class="m-2"
                  placeholder="选择标注任务"
                  popper-class="dropdown"
                  style="width: 300px"
                >
                  <el-option
                    v-for="item in options"
                    :key="item.id"
                    :label="item.title"
                    :value="item.id"
                    @click="getFeatureData"
                  />
                </el-select>
              </el-form-item>
            </transition>
            <transition name="el-fade-in">
              <el-form-item
                label="选择特征数据类型："
                prop="data_format"
                v-if="formatValue.length > 0"
              >
                <el-select
                  v-model="formLabelAlign.data_format"
                  class="m-2"
                  placeholder="请选择特征数据类型"
                  popper-class="dropdown"
                  style="width: 300px"
                >
                  <el-option
                    v-for="item in formatValue"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </transition>
          </div>
          <el-form-item
            v-if="seDataChoose == 'userData'"
            label=""
            prop="file_ids"
            ref="imageOfFrom"
          >
            <el-upload
              class="upload-demo uploadBox"
              drag
              :file-list="
                platformFeatureSetUploadStore.vueUploadComponentFileList
              "
              :auto-upload="false"
              accept=".zip"
              :on-change="handleFileChanged"
              style="width: 300px"
              :limit="1"
              :on-exceed="handleExceed"
            >
              <div class="el-upload__text uploadBoxBtn">
                <el-image :src="imgUrl" fit />
                <div style="color: #333333; font-size: 14px">
                  点击上传文件按钮，或拖拽文件到这里
                </div>
                <div>支持上传文件格式：zip</div>
              </div>
            </el-upload>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button
              v-if="!store.quickStart.quickFlow"
              @click="resetForm(ruleFormRef)"
              style="background-color: #fff !important"
              >取消</el-button
            >
            <el-button
              v-if="!store.quickStart.quickFlow"
              type="primary"
              @click="submitConfirm(ruleFormRef)"
            >
              确认
            </el-button>
            <el-button
              v-if="store.quickStart.quickFlow"
              type="primary"
              @click="submitConfirm(ruleFormRef)"
            >
              下一步
            </el-button>
          </span>
        </template>
      </el-dialog>
      <el-dialog
        v-model="dialogSetData"
        title="编辑特征库"
        width="500"
        :show-close="false"
        @close="resetForm(setDataRef)"
        :close-on-click-modal="false"
      >
        <box-loading v-if="loading" @click.stop></box-loading>
        <el-form
          ref="setDataRef"
          :model="setDataForm"
          :rules="setDataRules"
          label-position="right"
          label-width="130px"
          style="max-width: 460px"
        >
          <el-form-item label="特征库名称：" prop="title">
            <el-input
              v-model.trim="setDataForm.title"
              style="width: 300px"
              placeholder="请输入特征库名称"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button
              @click="resetForm(setDataRef)"
              style="background-color: #fff !important"
              >取消</el-button
            >
            <el-button type="primary" @click="submitConfirm(setDataRef)">
              提交
            </el-button>
          </span>
        </template>
      </el-dialog>
      <el-dialog
        v-model="dialogSplitData"
        title="特征库拆分"
        width="600"
        :show-close="false"
        @close="resetForm(splitDataRef)"
        :close-on-click-modal="false"
      >
        <box-loading v-if="loading" @click.stop></box-loading>
        <div class="splitTitle">
          <div>
            <el-icon
              style="
                color: #3d5ce4;
                display: inline-block;
                vertical-align: middle;
                margin-top: -3px;
                margin-right: 3px;
                font-size: 20px;
              "
            >
              <WarningFilled /> </el-icon
            >提示：
          </div>
          <div style="margin-left: 28px; color: #666666e6">
            1、当存在多个特征集时，会合并特征集数据
          </div>
          <div style="margin-left: 28px; color: #666666e6">
            2、文件类型数据默认读取首行数据为表头数据，多数据集请确保表头字段内容一致
          </div>
          <div style="margin-left: 28px; color: #666666e6">
            3、图片、视频帧类型数据会统一按照PASCAL
            VOC格式进行打包，如图片较多，任务执行时间较长，请耐心等待
          </div>
        </div>
        <el-form
          ref="splitDataRef"
          :model="splitDataForm"
          :rules="splitDataRules"
          label-position="right"
          label-width="125px"
          style="max-width: 600px"
        >
          <el-form-item
            label="训练验证比例："
            prop="train_ratio"
            class="inputBox"
          >
            <div class="row" style="width: 170px">
              <div class="col col-3">训练：</div>
              <div class="col">
                <el-input
                  type=""
                  v-model.trim="splitDataForm.train_ratio"
                  style="width: 100px"
                  placeholder="0-1"
                  @blur="numberSplit('train_ratio')"
                  @keyup.enter="numberSplit('train_ratio')"
                />
              </div>
            </div>
            <el-form-item label="" prop="validate_ratio">
              <div class="row" style="width: 170px">
                <div class="col col-3">验证：</div>
                <el-input
                  v-model="splitDataForm.validate_ratio"
                  style="width: 100px"
                  placeholder="0-1"
                  @blur="numberSplit('validate_ratio')"
                  @keyup.enter="numberSplit('validate_ratio')"
                />
              </div>
            </el-form-item>
            <el-tooltip
              class="box-item"
              effect="light "
              content="输入一个参数的值，另一个参数会自动计算"
              placement="right-start"
            >
              <el-button
                style="
                  transform: scale(0.75);
                  transform-origin: left;
                  margin: 0 0 0 -10px;
                  font-size: 18px;
                  color: #333;
                  border-color: #333;
                "
                size="small"
                circle
                >?
              </el-button>
            </el-tooltip>
          </el-form-item>
          <el-form-item label="是否随机：" prop="is_random">
            <el-switch v-model="splitDataForm.is_random" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button
              @click="resetForm(splitDataRef)"
              style="background-color: #fff !important"
              >取消</el-button
            >
            <el-button type="primary" @click="submitConfirm(splitDataRef)">
              提交
            </el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 删除 -->
      <q-dialog v-model="dialogDeleteData">
        <q-card style="width: 450px; height: 170px">
          <q-card-section>
            <div class="text-h6" style="font-size: 17px">
              <el-icon
                style="
                  color: #ffa940;
                  display: inline-block;
                  vertical-align: middle;
                  margin-top: -3px;
                  font-size: 25px;
                "
              >
                <WarningFilled />
              </el-icon>
              <span style="font-size: 16px; margin-left: 5px; color: #ffa940"
                >删除提醒</span
              >
            </div>
          </q-card-section>
          <q-card-section class="q-pt-none" style="padding-left: 45px">
            <div style="line-height: 22px; color: #666">
              确定删除本特征集吗？删除后不可恢复，请谨慎操作！
            </div>
          </q-card-section>
          <q-card-actions
            align="right"
            class="text-primary"
            style="margin-right: 20px; margin-top: 10px"
          >
            <el-button
              @click="deleteData"
              style="background-color: #fff !important"
              >确认删除</el-button
            >
            <el-button type="primary" v-close-popup>放弃删除</el-button>
          </q-card-actions>
        </q-card>
      </q-dialog>

      <!-- 下载 -->
      <q-dialog v-model="downloadDialog">
        <q-card style="width: 450px; height: 170px">
          <q-card-section>
            <div class="text-h6" style="font-size: 17px">
              <el-icon
                style="
                  color: #3d5ce4;
                  display: inline-block;
                  vertical-align: middle;
                  margin-top: -3px;
                  font-size: 25px;
                "
              >
                <WarningFilled />
              </el-icon>
              <span
                style="
                  font-size: 16px;
                  margin-left: 5px;
                  color: #3d5ce4;
                  font-weight: 500;
                "
                >下载提醒</span
              >
            </div>
          </q-card-section>
          <q-card-section class="q-pt-none" style="padding-left: 45px">
            <div style="line-height: 22px; color: #666">
              确定下载本特征集吗？
            </div>
          </q-card-section>
          <q-card-actions
            align="right"
            class="text-primary"
            style="margin-right: 20px; margin-top: 10px"
          >
            <el-button v-close-popup style="background-color: #fff !important"
              >放弃</el-button
            >
            <el-button type="primary" @click="downloadHandle"
              >继续下载</el-button
            >
          </q-card-actions>
        </q-card>
      </q-dialog>
      <el-dialog
        v-model="platformReUploadStore.reUploadModal"
        title="继续上传"
        width="60%"
        :modal="false"
        :before-close="closeContinueUploadModal"
        destroy-on-close
      >
        <el-table
          :data="dialogContinueUpload.fileList"
          height="377"
          style="width: 100%"
          :header-cell-style="{
            background: '#f9f9f9',
            color: '#333333',
            fontWeight: '500',
            fontSize: '14px',
            textAlign: 'left',
            height: '56px',
          }"
          v-loading="!dialogContinueUpload.fileList.length"
        >
          <el-table-column
            prop="row_name"
            label="文件名称"
            width="100"
            show-overflow-tooltip
          />
          <el-table-column prop="total_size_calc" label="文件大小" />
          <el-table-column prop="dataset_title" label="所属数据集" />
          <el-table-column prop="version_title" label="所属版本" />
          <el-table-column prop="create_time" label="上传时间" width="180" />

          <el-table-column prop="progress" label="已经上传进度">
            <template #default="scope">
              <el-progress
                :stroke-width="10"
                :percentage="scope.row.progress"
              />
              <!--              <template v-if="scope.row.progress != 100">-->
              <!--                <el-progress :stroke-width="10" :percentage="scope.row.progress"/>-->
              <!--              </template>-->
              <!--              <template v-else>-->
              <!--                <el-icon color="#21ba45">-->
              <!--                  <Check/>-->
              <!--                </el-icon>-->
              <!--              </template>-->
            </template>
          </el-table-column>
          <el-table-column label="操作" prop="progress">
            <template #default="scope">
              <template
                v-if="
                  dialogContinueUpload.fileListStatusControl[
                    scope.row.feature_set_id
                  ][scope.row.row_name].isPassCheck
                "
              >
                <el-icon color="#21ba45">
                  <Check />
                </el-icon>
              </template>
              <template v-else>
                <el-upload
                  class="upload-demo"
                  :auto-upload="false"
                  :show-file-list="false"
                  :onChange="(uploadFile: UploadFile, uploadFiles: UploadFiles) =>
                  handleContinueChange(uploadFile, uploadFiles, scope.row.row_name,scope.row.total_size, scope.row.feature_set_id )"
                >
                  <q-btn
                    round
                    dense
                    flat
                    color="grey-8"
                    style="display: flex; align-items: center"
                  >
                    <el-icon>
                      <CaretRight />
                    </el-icon>
                    <q-tooltip effect="light"
                      >选择相同的文件，继续上传</q-tooltip
                    >
                  </q-btn>
                </el-upload>
              </template>
            </template>
          </el-table-column>
        </el-table>
        <template #footer>
          <span class="dialog-footer">
            <el-button type="primary" @click="startContinueUpload">
              继续创建
            </el-button>
          </span>
        </template>
      </el-dialog>
      <div class="temp" v-if="tempShow"></div>
    </div>
  </q-page>
</template>

<script setup lang="ts">
import { Search } from '@element-plus/icons-vue';
import type { FormInstance, FormRules } from 'element-plus';
import {
  ElMessage,
  ElMessageBox,
  ElNotification,
  UploadFile,
  UploadFiles,
} from 'element-plus';
import {
  addFeatureset,
  deleteFeatureset,
  downloadFeatureset,
  featureSplitData,
  getExportFormat,
  getFeatureset,
  getTasksLabeled,
  setFeatureset,
  validateFeaturesetName,
} from 'src/api/dataset';
import { putQuickStartFlow } from 'src/api/project';
import StatusBoxCpn from 'src/components/StatusBoxCpn.vue';
import boxLoading from 'src/components/boxLoading.vue';
import { dataSetStore } from 'src/stores/dataSet';
import { onMounted, reactive, ref, shallowRef, watch } from 'vue';
import { useRouter } from 'vue-router';

import imgUrl from 'assets/dataSet/grayUpload.png';
import {
  BaseFeatureSetReq,
  createFeatureSet,
  getUnCompleteFileList,
} from 'src/api/featureSet';
import { dataTypeData } from 'src/utils/useData';
import { usePlatformReUploadFeatureSetStore } from 'stores/platform-featureset-reupload';
import {
  CurrentFeatureSet,
  UploadFeatureSetList,
  usePlatformFeatureSetUploadStore,
} from 'stores/platform-featureset-upload';

const userStatus = JSON.parse(localStorage.getItem('user') || '{}').status; //判断用户是否是项目创建人或项目管理员
const userInfoName = localStorage.getItem('username'); //获取用户登录的用户名
const router = useRouter();
const projectId = router.currentRoute.value.params.project_id;
const typeValue = ref('');
const loading = ref(true);
const searchName = ref('');
const dialogAddData = ref(false);
const dialogSetData = ref(false);
const dialogSplitData = ref(false);
const dialogDeleteData = ref(false);
const downloadDialog = ref(false);
const downloadIdData = ref(0);
const featuresetIdValue = ref(0);
const options = shallowRef(<any>[]);
const formatValue = shallowRef(<any>[]);
const ruleFormRef = ref<FormInstance>();
const setDataRef = ref<FormInstance>();
const splitDataRef = ref<FormInstance>();
const featureset_id = ref();
const imageOfFrom = ref();
const paramObj = shallowRef();
const platformReUploadStore = usePlatformReUploadFeatureSetStore();
const platformUploadStore = usePlatformFeatureSetUploadStore();
const tempShow = ref(false);
const formLabelAlign = reactive({
  title: '',
  description: '',
  data_format: null,
  label_task: '',
  dataset_type: '',
  file_ids: <any>[],
});
const setDataForm = reactive({
  title: '',
});

const splitDataForm = reactive({
  train_ratio: '',
  validate_ratio: '',
  is_random: false,
});

const tableData = shallowRef({
  count: 0,
  results: [],
});
const closeContinueUploadModal = (done: any) => {
  platformUploadStore.setVueUploadComponentFileListEmpty();
  done();
};

const cellStyle = () => {
  return { height: '56px' };
};
const seDataChoose = ref('labelData');
const tips = ref(false);
const pageData = dataSetStore().pageData;
const uploadFileList: any = ref([]);
const fileType = ref('zip');
const store = dataSetStore();

onMounted(() => {
  if (store.quickStart.quickFlow) {
    store.setQuickStart({
      tipsPopup: true,
      quickFlow: true,
      flowNumber: store.quickStart.flowNumber,
    });
  }
});
// 监听快速入门点击新建按钮
watch(
  () => store.quickStart,
  (newEl, oldEl) => {
    if (!newEl.tipsPopup && newEl.quickFlow) {
      showDialog('dialogAddData', 0, '', '');
    }
  }
);
// 拆分时数据比例设置，只允许最多一位小数
function numberSplit(name: keyof typeof splitDataForm) {
  let checkBoolean = inputCheck(splitDataForm[name]);
  let dataLength: any = splitDataForm[name];
  if (
    dataLength.length > 0 &&
    checkBoolean == true &&
    parseFloat(dataLength) <= 1
  ) {
    let residueNum = parseFloat((1 - parseFloat(dataLength)).toFixed(1));
    if (name == 'train_ratio') {
      splitDataForm.validate_ratio = residueNum + '';
    } else {
      splitDataForm.train_ratio = residueNum + '';
    }
  } else if (dataLength.length >= 4) {
    ElMessage.error('最多支持一位小数,请重新输入');
    splitDataForm.train_ratio = '';
    splitDataForm.validate_ratio = '';
  } else if (
    (dataLength.length == 2 ||
      checkBoolean == false ||
      parseFloat(dataLength) > 1) &&
    dataLength.length != 0
  ) {
    ElMessage.error('数值有误，请输入区间内的数值');
    splitDataForm.train_ratio = '';
    splitDataForm.validate_ratio = '';
  }
}

watch(seDataChoose, (newData, oldData) => {
  init();
});

// 正则校验输入的数值
function inputCheck(inputValue: any) {
  var re = /(^[0-9]{1,1}$)|(^[0-9]{1,2}[\.]{1}[0-9]{1,1}$)/;
  return re.exec(inputValue) != null;
}

const dialogContinueUpload = reactive({
  fileList: [] as UploadFeatureSetList[],
  fileListStatusControl: {} as Record<
    string,
    Record<string, { isPassCheck: boolean }>
  >,
  curContinueInfo: {} as BaseFeatureSetReq,
});

const handleContinueUpload = async (req: BaseFeatureSetReq) => {
  platformReUploadStore.openModal();
  const fileListResponse = await getUnCompleteFileList(req);
  const lists = fileListResponse.data;
  const listControl: Record<string, Record<string, any>> = {};
  lists.forEach((list) => {
    listControl[String(list.feature_set_id)] =
      listControl[String(list.feature_set_id)] || {};
    listControl[String(list.feature_set_id)][list.row_name] = {
      isPassCheck: false,
    };
    platformReUploadStore.mapperUploadId(
      String(list.feature_set_id),
      String(list.upload_id),
      list.row_name
    );
  });

  platformReUploadStore.setReUploadList(lists);
  dialogContinueUpload.fileListStatusControl = listControl;
  dialogContinueUpload.fileList = lists;
  dialogContinueUpload.curContinueInfo = { ...req };
};

const startContinueUpload = async () => {
  let isNoPass = false;
  Object.keys(dialogContinueUpload.fileListStatusControl).forEach(
    (feature_set_id) => {
      Object.keys(
        dialogContinueUpload.fileListStatusControl[feature_set_id]
      ).forEach((filename) => {
        if (
          dialogContinueUpload.fileListStatusControl[feature_set_id][filename]
            .isPassCheck == false
        ) {
          isNoPass = true;
        }
      });
    }
  );
  if (isNoPass) {
    ElMessage.warning('请将所有的文件上传之后，在继续创建');
    return;
  }
  await platformReUploadStore.startContinueUpload(
    dialogContinueUpload.curContinueInfo
  );
};

const handleContinueChange = (
  uploadFile: UploadFile,
  uploadFiles: UploadFiles,
  filename: string,
  filesize: number,
  feature_set_id: string
) => {
  if (uploadFile.name !== filename || uploadFile?.raw?.size !== filesize) {
    ElMessage.warning('请上传和之前一样的文件');
    return;
  }
  dialogContinueUpload.fileListStatusControl[feature_set_id][
    filename
  ].isPassCheck = true;
  platformUploadStore.pushFileList(uploadFile);
};

const validateTitle = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error('特征集名称不能为空'));
    return;
  }
  let params = {
    title: formLabelAlign.title,
  };
  validateFeaturesetName(projectId, params)
    .then((res: any) => {
      if (res.data.msg) {
        callback(new Error(res.data.msg));
      }
      callback();
    })
    .catch((err: any) => {
      callback(new Error('校验接口报错'));
    });
};

const rules = reactive<FormRules>({
  title: [{ required: true, validator: validateTitle, trigger: 'blur' }],
  dataset_type: [
    { required: true, message: '请选择标注场景', trigger: 'change' },
  ],
  data_format: [
    { required: true, message: '请选择特征数据类型', trigger: 'change' },
  ],
  label_task: [
    { required: true, message: '请选择标注任务', trigger: 'change' },
  ],
  file_ids: [
    {
      required: false,
      message: '特征集数据上传不能为空',
      trigger: ['blur', 'change'],
    },
  ],
});

const validateTitle1 = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error('特征集名称不能为空'));
    return;
  }
  let params = {
    title: setDataForm.title,
  };
  validateFeaturesetName(projectId, params)
    .then((res: any) => {
      if (res.data.msg) {
        callback(new Error(res.data.msg));
      }
      callback();
    })
    .catch((err: any) => {
      callback(new Error('校验接口报错'));
    });
};
const setDataRules = reactive<FormRules>({
  title: [{ required: true, validator: validateTitle1, trigger: 'blur' }],
});
const checkTrainratio = (rule: any, value: any, cb: any) => {
  if (value === '0') {
    cb(new Error('训练比例不能为0'));
  } else if (!value) {
    cb(new Error('训练比例不能为空'));
  } else {
    cb();
  }
};
const splitDataRules = reactive<FormRules>({
  train_ratio: [
    { required: true, validator: checkTrainratio, trigger: 'blur' },
  ],
  validate_ratio: [
    {
      required: true,
      message: '验证比例不能为空',
      trigger: ['blur', 'change'],
    },
  ],
  is_random: [{ required: true, message: '', trigger: 'change' }],
});

const platformFeatureSetUploadStore = usePlatformFeatureSetUploadStore();

getDataList(); //获取特征集列表数据

watch(
  () => platformFeatureSetUploadStore.platformFeatureSetStatusChange,
  async () => {
    loading.value = true;
    await getDataList();
    tempShow.value = !tempShow.value;
    loading.value = false;
  }
);

function showDialog(
  str: string,
  featuresetId: number,
  title: string,
  description: string
) {
  if (featuresetId > 0) featureset_id.value = featuresetId;
  if (str == 'dialogAddData') dialogAddData.value = true;
  if (str == 'dialogSetData') {
    setDataForm.title = title;
    dialogSetData.value = true;
  }
  if (str == 'dialogSplitData') dialogSplitData.value = true;
}
// 特征库数据下载
function downLoadData(id: number, fileStr: string) {
  downloadDialog.value = true;
  downloadIdData.value = id;
}
function downloadHandle() {
  downloadDialog.value = false;
  downloadFeatureset(projectId, downloadIdData.value).then((res: any) => {
    let blob = new Blob([res.data], { type: 'application/octet-stream' });
    let downloadElement = document.createElement('a');
    let href = window.URL.createObjectURL(blob);
    downloadElement.href = href;
    downloadElement.download = decodeURI(res.headers.filename);
    document.body.appendChild(downloadElement);
    downloadElement.click();
    document.body.removeChild(downloadElement);
    window.URL.revokeObjectURL(href);
  });
}
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  init();
  if (dialogAddData.value) dialogAddData.value = false;
  if (dialogSetData.value) dialogSetData.value = false;
  if (dialogSplitData.value) dialogSplitData.value = false;
};

const submitConfirm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      // 添加特征库
      if (dialogAddData.value) {
        const { dataset_type, file_ids, ...postObj } = formLabelAlign;
        let obj = null;
        if (seDataChoose.value == 'labelData') {
          obj = postObj;
          loading.value = true;
          addFeatureset(projectId, obj)
            .then((res: any) => {
              ElMessageBox.alert('创建特征库成功', '提示', {
                confirmButtonText: '知道了',
                autofocus: false,
              }).then(() => {
                if (store.quickStart.quickFlow) {
                  putQuickStartFlow(projectId, { stage: 4 }).finally(() => {
                    router.push({
                      name: 'quick-start',
                      params: { project_id: projectId },
                    });
                  });
                } else {
                  init();
                  getDataList();
                }
                dialogAddData.value = false;
                formEl.resetFields();
              });
            })
            .finally(() => {
              loading.value = false;
            })
            .catch((error) => {
              console.log(error);
              loading.value = false;
              ElMessage.error('error');
            });
        } else {
          try {
            const createFeatureSetResponse = await createFeatureSet(
              projectId as string,
              {
                title: formLabelAlign.title,
                description: formLabelAlign.description,
              }
            );
            const feature_set_id = createFeatureSetResponse.data.feature_set_id;

            const currentFeatureSet: CurrentFeatureSet = {
              feature_set_id: String(feature_set_id),
              project_id: projectId as string,
            } as const;
            await platformFeatureSetUploadStore.startUploadPrepare(
              currentFeatureSet
            );
            dialogAddData.value = false;
            await platformFeatureSetUploadStore.startUploadStart(
              currentFeatureSet
            );
            // paramObj.value.append('title', formLabelAlign.title);
            // paramObj.value.append('description', formLabelAlign.description);
            // obj = paramObj.value;
          } catch (err) {
            console.log;
            ElMessage.error('创建特征集失败');
          }
        }
      }
      // 修改特征库
      if (dialogSetData.value) {
        setFeatureset(projectId, featureset_id.value, setDataForm)
          .then((res: any) => {
            ElNotification({
              title: 'Success',
              message: '修改成功',
              type: 'success',
            });
            getDataList();
            dialogSetData.value = false;
          })
          .finally(() => {
            loading.value = false;
          })
          .catch((error) => {
            console.log(error);
          });
      }
      // 拆分特征库
      if (dialogSplitData.value) {
        featureSplitData(projectId, featureset_id.value, splitDataForm)
          .then((res: any) => {
            ElNotification({
              title: 'Success',
              message: '特征库拆分成功',
              type: 'success',
            });
            dialogSplitData.value = false;
          })
          .catch((error) => {
            console.log(error);
          })
          .finally(() => {
            loading.value = false;
          });
      }
    } else {
      console.log('error submit!', fields);
    }
  });
};

async function getDataList() {
  loading.value = true;
  let obj: any = {};
  if (typeValue.value != '') obj.source = typeValue.value;
  if (searchName.value != '') obj.title = searchName.value;
  obj = Object.assign(obj, pageData);
  const res = await getFeatureset(projectId, obj);
  tableData.value = res.data;
  loading.value = false;
}

function getDataset() {
  dataSetStore().setPageData(1);
  getDataList();
}
function toDetailPage(featuresetId: number) {
  dataSetStore().setFeature(featuresetId);
  router.push({
    name: 'featureset-detail',
    params: { project_id: projectId, test: 'lalla' },
  });
}
// 数据初始化
function init() {
  uploadFileList.value = [];
  formatValue.value = [];
  options.value = [];
  formLabelAlign.label_task = '';
  formLabelAlign.data_format = null;
  paramObj.value = null;
}
// 获取标注任务数据
function getLabelData() {
  init();
  getTasksLabeled(projectId, { label_type: formLabelAlign.dataset_type })
    .then((res: any) => {
      options.value = res.data;
      if (options.value.length > 0) tips.value = false;
      else tips.value = true;
    })
    .catch((error) => {
      console.log(error);
    })
    .finally(() => {
      loading.value = false;
    });
}
// 获取特征数据类型
function getFeatureData() {
  getExportFormat(projectId, formLabelAlign.label_task)
    .then((res: any) => {
      let datalist = res.data.map((item: any) => {
        if (item.title === 'Pascal VOC XML') {
          item.title = 'Pascal';
        }
        return item;
      });
      let data1 = datalist.filter((item: any) => {
        if (item.title === 'COCO' || item.title === 'Pascal') {
          return false;
        } else {
          return true;
        }
      });
      let data2 = datalist.filter((item: any) => {
        if (item.title === 'COCO' || item.title === 'Pascal') {
          return true;
        } else {
          return false;
        }
      });
      let total = data2.concat(data1);
      formatValue.value = mapArr(total);
    })
    .catch((error: any) => {
      console.log(error);
    })
    .finally(() => {
      loading.value = false;
    });
}
// 处理接口返回数据
const mapArr = (arr: Array<any>) => {
  let filterArr = arr.map((item) => {
    let obj = {
      label: item.title,
      value: item.id,
    };
    return obj;
  });
  return filterArr;
};
// 删除特征库
function deleteProject(featuresetId: number) {
  dialogDeleteData.value = true;
  featuresetIdValue.value = featuresetId;
}
function deleteData() {
  deleteFeatureset(projectId, featuresetIdValue.value)
    .then(() => {
      ElMessage.success('删除成功！');
      getDataList();
    })
    .finally(() => {
      dialogDeleteData.value = false;
      loading.value = false;
    });
}
function changePage(currentPage: any) {
  dataSetStore().setPageData(currentPage);
  getDataList();
}
// 文件上传
function uploadFile(obj: any) {
  imageOfFrom.value.clearValidate();
  paramObj.value = new FormData();
  paramObj.value.append('file', obj.file);
  formLabelAlign.file_ids.push(1);
}

function checkFileType(file: any): boolean {
  const fileName = file.name;
  const fileTypeName = fileName.substring(fileName.lastIndexOf('.') + 1);
  if (!fileType.value.includes(fileTypeName)) {
    ElMessage.warning(`上传类型错误，请选择${fileType.value}格式文件`);
    return false;
  }
  let isLt2k = file.size / 1024 / 1024 / 1024 < 2 ? '1' : '0';
  if (isLt2k == '0') {
    ElMessage.warning(`上传文件过大，请选择小于2G的文件`);
    return false;
  }
  return true;
}

const handleFileChanged = (
  uploadFile: UploadFile,
  uploadFiles: UploadFiles
) => {
  if (!checkFileType(uploadFile)) {
    uploadFiles.pop();
    return;
  }
  platformFeatureSetUploadStore.setFileList(uploadFile);
};

const handleExceed = () => {
  ElMessage.warning('文件数量不能超过一个');
};

function setErrorTips(str: any) {
  if (typeof str == 'string') {
    ElMessage.error('自定义数据特征库，不支持拆分操作');
  }
}
// 上传文件校验

// 删除上传文件列表的某个值
function removeListData(file: any, fileList: any) {
  formLabelAlign.file_ids.splice(0, 1);
}
</script>

<style scoped lang="scss">
.nav {
  display: flex;
  align-items: center;
  padding-left: 20px;
  cursor: pointer;
  background-color: #f6f8fa;
  height: 46px;

  ::v-deep .el-breadcrumb {
    display: flex;
    align-items: center;
  }
}

//超出显示小圆点 start
.overFlowEllipsis {
  width: 180px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  word-break: break-all;
  text-align: left;
}
// end

.wrapBox {
  padding: 0 !important;

  .datasetBox {
    margin: 0 20px;

    .contentBox_title {
      color: var(--title);
      font-weight: 500;
      font-size: 16px;
      padding: 15px 15px;
      border-bottom: 1px solid #e5e6eb;
      background-color: #ffffff !important;
    }

    .contentBox {
      padding: 12px;
      background-color: #ffffff !important;
    }
  }
}

//下拉框背景颜色
.dropdown {
  .el-select-dropdown__item.selected {
    font-weight: 500 !important;
  }

  .el-select-dropdown__item.hover,
  .el-select-dropdown__item:hover {
    background: #3d5ce41a;
    color: #3d5ce4;
    font-weight: 400;
    font-size: 14px;
    text-align: left;
  }
}

//面包屑斜杆
::v-deep .el-breadcrumb__separator {
  font-size: 12px !important;
  color: #c9cdd4 !important;
}

//面包屑字体颜色
::v-deep .el-breadcrumb__inner {
  color: #666 !important;
}
//分页输入框跳转不限制
::v-deep disabled,
::v-deep .disabled *,
::v-deep [disabled],
::v-deep [disabled] * {
  outline: 10px !important;
  cursor: pointer !important;
}

//tab选项卡 start
::v-deep .el-radio-button__original-radio:checked + .el-radio-button__inner {
  background: #3d5ce41a !important;
  color: #3d5ce4 !important;
}

::v-deep .el-radio-button__inner {
  width: 150px !important;
  background: #fafafa !important;
}

//end
::v-deep .el-dialog__header {
  border-bottom: 1px solid rgb(234, 234, 234);
}

::v-deep .el-dialog__title {
  font-weight: 500;
  color: #333;
}

.rightBox {
  position: absolute;
  right: 0;
}

.splitTitle {
  background: #f4f6ff;
  border: 1px solid #b6ccff;
  padding: 10px;
  border-radius: 3px;
  margin-bottom: 20px;
  margin-top: -20px;
  font-size: 12px;
  color: #333333;

  i {
    font-style: initial;
  }

  div {
    margin-bottom: 3px;
  }
}

.inputBox {
  &::v-deep .el-form-item__error {
    left: 42px;
  }

  &::v-deep .el-input.is-disabled {
    .el-input__inner {
      -webkit-text-fill-color: #666;
      opacity: 1 !important;
    }

    .el-input__wrapper {
      background: initial;
    }
  }

  &::v-deep(.el-input__inner) {
    &::placeholder {
      color: #bbb;
      -webkit-text-fill-color: #bbb;
    }
  }
}

.errorBorder {
  &::v-deep .el-input__wrapper {
    box-shadow: 0 0 0 1px #ff5656 inset !important;
  }
}

.uploadBox {
  .uploadBoxBtn {
    text-align: center;

    .el-image {
      width: 56px;
      height: 56px;
      display: block;
      margin: 0 auto;
    }

    div {
      font-size: 12px;
      height: 20px;
    }
  }
}
</style>
